package com.example.stringbufferlogger.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.stringbufferlogger.Utils.ExcelUtils;
import com.example.stringbufferlogger.mapper.InterfaceMappingConfigMapper;
import com.example.stringbufferlogger.Utils.OSSUtil;
import com.example.stringbufferlogger.service.FileService;
import com.example.stringbufferlogger.service.InterfaceMappingConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service; // 引入注解
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private ExcelUtils excelUtils;

    @Autowired
    private InterfaceMappingConfigMapper interfaceMappingConfigMapper;

    @Override
    public Map<String, Object> handleFileUpload(MultipartFile file, String requestId,String interfaceUrl) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 验证requestId是否为空
            if (requestId == null || requestId.trim().isEmpty()) {
                result.put("status", "error");
                result.put("message", "requestId is required");
                return result;
            }

            // 2. 获取文件扩展名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 3. 生成保存的文件名（requestId + 扩展名）
            String savedFileName = requestId + fileExtension;

            // 4. 处理文件名冲突（如果文件已存在）
            int counter = 1;
            while (OSSUtil.isFileExist(savedFileName)) {
                savedFileName = requestId + "_" + counter + fileExtension;
                counter++;
            }
            String type = interfaceMappingConfigMapper.checkPathType(interfaceUrl);
            // 5. 直接上传文件到OSS
            OSSUtil.uploadFileFromStream(file.getInputStream(), savedFileName, type);

//            //根据url来区文件来源（新旧系统）
//            String recordType = interfaceMappingConfigMapper.checkPathType(interfaceUrl);
//            // 6. 文件数据入库
//            excelUtils.processExcel(file.getInputStream(),interfaceUrl,requestId,recordType);


            // 7. 返回成功响应
            result.put("status", "success");
            result.put("requestId", requestId);
            result.put("savedFilename", savedFileName);
            result.put("fileSize", file.getSize());
            result.put("originalFilename", originalFilename);

        } catch (IOException e) {
            result.put("status", "error");
            result.put("message", "File upload failed: " + e.getMessage());
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public ResponseEntity<Map<String, Object>> receiveDownload(MultipartFile file, String metadataJson,String reqId,String interfaceUrl) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 1. 解析元数据
            JSONObject metadata = JSONObject.parseObject(metadataJson);
            String fileName = metadata.getString("fileName");
            String contentType = metadata.getString("contentType");
            long size = metadata.getLongValue("size");

            // 2. 验证文件大小
            if (file.getSize() != size) {
                response.put("success", false);
                response.put("message", "文件大小不匹配");
                return ResponseEntity.badRequest().body(response);
            }
            String safeFileName = generateSafeFileName(fileName);

             String type = interfaceMappingConfigMapper.checkPathType(interfaceUrl);

            // 4. 直接上传文件到OSS
            OSSUtil.uploadFileFromStream(file.getInputStream(), safeFileName,type);

//            //根据url区分文件来源（新旧系统）
//            String recordType = interfaceMappingConfigMapper.checkPathType(interfaceUrl);
//            // 5. 文件数据入库
//            excelUtils.processExcel(file.getInputStream(),interfaceUrl,reqId,recordType);

            // 6. 返回成功响应
            response.put("success", true);
//            response.put("fileId", fileId);
            response.put("safeFileName", safeFileName);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "文件接收失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(response);
        }
    }

    private String generateSafeFileName(String originalName) {
        // 替换可能引起问题的字符
        String safeName = originalName.replaceAll("[^a-zA-Z0-9.-]", "_");

        // 添加时间戳防止冲突
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sdf.format(new java.util.Date());

        int dotIndex = safeName.lastIndexOf('.');
        if (dotIndex > 0) {
            return safeName.substring(0, dotIndex) + safeName.substring(dotIndex);
        } else {
            return safeName;
        }
    }
}
